package org.example;

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

import java.util.ArrayDeque;
import java.util.Queue;

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Queue<Node> queue = new ArrayDeque<Node>();
        queue.offer(root);
        int curLevelNodes = 1;
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            for (int i = 1; i < curLevelNodes; i++) {
                Node next = queue.poll();
                cur.next = next;
                if (cur.left != null) {
                    queue.offer(cur.left);
                    queue.offer(cur.right);
                }
                cur = next;
            }
            if (cur.left != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
            cur.next = null;
            curLevelNodes *= 2;
        }
        return root;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}